let tableIns;
let tree;
layui.use(['element','upload', 'form', 'table', 'layer', 'laydate', 'tree', 'util'], function () {
    let table = layui.table;
    let form = layui.form;//select、单选、复选等依赖form
    let element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
    let laydate = layui.laydate,upload = layui.upload;
    tree = layui.tree;
    let height = document.documentElement.clientHeight - 60;



    tableIns = table.render({
        elem: '#sellerTable'
       // , url: ctx + '/seller/sellerlist/page'
        , url: '/seller/sellerlist/page'
        , method: 'POST'
        //请求前参数处理
        , request: {
            pageName: 'page' //页码的参数名称，默认：page
            , limitName: 'rows' //每页数据量的参数名，默认：limit
        }
        , response: {
            statusName: 'flag' //规定数据状态的字段名称，默认：code
            , statusCode: true //规定成功的状态码，默认：0
            , msgName: 'msg' //规定状态信息的字段名称，默认：msg
            , countName: 'records' //规定数据总数的字段名称，默认：count
            , dataName: 'rows' //规定数据列表的字段名称，默认：data
        }
        //响应后数据处理
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            return {
                "flag": res.flag, //解析接口状态
                "msg": res.msg, //解析提示文本
                "records": data.records, //解析数据长度
                "rows": data.rows //解析数据列表
            };
        }
        , toolbar: '#sellerTableToolbar'
        , title: '商户列表'
        , cols: [[
            {field: 'sellerId', title: '商户ID', hide: true}
            , {field: 'sellerName', width:150,title: '商户名称'}
            , {field: 'sellerBaseInfo',title: '商户基本信息'}
            , {field: 'sellerPayInfo', width:200,title: '支付设置'}
            , {field: 'sellerManageInfo',title: '工商注册信息'}
            , {field: 'appKey',title: '加密信息', templet:function (d) {
            	if(d.appKey == undefined){
            		d.appKey = '无';
            	}
            	if(d.appSecret == undefined){
            		d.appSecret = '无';
            	}
        			return '<span > appKey：' + d.appKey + '</span> <br/>' +'<span >appSecret：' + d.appSecret + '</span>';
            }}
            , {field: 'sellerCompanyName', title: '公司全称', hide: true}
            , {field: 'sellerMobile',title: '手机', hide: true}
            , {field: 'sellerCity', title: '城市', hide: true}
            , {field: 'loadDate', title: '注册日期', hide: true}
            , {field: 'maxPay', title: '最大薪水', hide: true}
            , {field: 'minPay', title: '最小薪水', hide: true}
            , {field: 'taxPayerCode', title: '纳税人识别号', hide: true}
            , {field: 'sellerAddress', title: '地址', hide: true}
            , {field: 'sellerPhone', title: '电话', hide: true}
            , {field: 'sellerBank', title: '开户行名', hide: true}
            , {field: 'sellerBankAccount', title: '开户账号', hide: true}
            , {field: 'sellerState', title: '状态', hide: true}
            , {fixed: 'right', width:160, title: '操作', toolbar: '#sellerTableBar'}
        ]]
        , defaultToolbar: ['', '', '']
        , page: true
        , height: height
        , cellMinWidth: 80
    });


    layui.use('form', function(){
        var form = layui.form;
        var roleHtml = '';
        
        $.ajax({
            url : "/seller/info/list/serviceType",
            type : "post",
            dataType : "json",
            success : function(res){
            	
            	var serviceType = $("#serviceType").val();
                if(serviceType != undefined){
                	serviceType = serviceType.split(",");
                	$.inArray("信息技术服务*软件测试服务", serviceType);  //返回 3,
                }
                for(var i = 0;i<res.data.length;i++){
                	if($.inArray(res.data[i], serviceType) >= 0){
                		roleHtml += "<div class='div'><input type='checkbox' checked  name='role_id' title='" + res.data[i] + "' value='" + res.data[i] + "'></div>";               		
                	}else{
                		roleHtml += "<div class='div'><input type='checkbox' name='role_id' title='" + res.data[i] + "' value='" + res.data[i] + "'></div>";  
                	}
                }

                //渲染数据
                document.getElementById('role_id').innerHTML  = roleHtml;
                form.render('checkbox');
            }
        });


    });

    //头工具栏事件
    table.on('toolbar(display)', function (obj) {
        switch (obj.event) {
            case 'addData':
            	layer.open({
                    type: 2,
                    title: '新增商户',
                    closeBtn: 1, //显示关闭按钮
                    anim: 2,
                    area: ['800px', '450px'],
                    shadeClose: true, //开启遮罩关闭
                    content: '/seller/sellerinsert'
                });
                break;
            case 'importData':
            	layer.open({
                    type: 2,
                    title: '批量导入商户',
                    closeBtn: 1, //显示关闭按钮
                    anim: 2,
                    area: ['400px', '200px'],
                    shadeClose: true, //开启遮罩关闭
                    content: '/seller/sellerimport'
                });
                break;
            case 'query':
                let queryBySellerName = $("#queryBySellerName").val();
                let query = {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , done: function (res, curr, count) {
                        //完成后重置where，解决下一次请求携带旧数据
                        this.where = {};
                    }
                };
                if (queryBySellerName) {
                    //设定异步数据接口的额外参数
                    query.where = {sellerName: queryBySellerName};
                }
                tableIns.reload(query);
                $("#queryBySellerName").val(queryBySellerName);
                break;
        }
    });

    //监听行工具事件
    table.on('tool(display)', function (obj) {
        let data = obj.data;
        //删除
        if (obj.event === 'del') {
            layer.confirm('确认删除吗？', function (index) {
                //向服务端发送删除指令
                $.post("/seller/operation", //ctx +
                		{sellerId:data.sellerId,sellerState:'D'}, function (data) {
                	$("#queryBySellerNameBtn").click();
                    layer.close(index);
                })
            });
        }
        //编辑
        else if (obj.event === 'edit') {
            layer.open({
                type: 2,
                title: '编辑商户',
                closeBtn: 1, //显示关闭按钮
                anim: 2,
                area: ['800px', '450px'],
                shadeClose: true, //开启遮罩关闭
                content: '/seller/sellerinfo?sellerId='+data.sellerId,
                success: function(layero, index){

                }
            });
        }
        //下载
        else if (obj.event === 'downFile') {
            window.open("/seller/downFile?fileName="+data.contractFile);
        }
    });



    //图片上传
    var formDatas = new FormData(),
        picFilese = '',
        picObjse = document.getElementById("AjaxFileData");
    $("#AjaxFileData").change(function(){
        //$("#picShow").attr("src",URL.createObjectURL($(this)[0].files[0]));
        var file = $('#AjaxFileData').get(0).files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload=function(e){
            //读取成功后返回的一个参数e，整个的一个进度事件
            console.log(e);
            //选择所要显示图片的img，要赋值给img的src就是e中target下result里面
            //的base64编码格式的地址
            $('#picShow').attr("height","200");
            $('#picShow').get(0).src = e.target.result;
        }
        console.log('picObjs.value-1--v',picObjse.value);

        if(picObjse.value != ""){ //
            picFilese = $("#AjaxFileData")[0].files[0];
            var imgType = (picFilese.name.substr(picFilese.name.lastIndexOf("."))).toLowerCase();
            if (imgType != ".jpg" && imgType != ".gif" && imgType != ".jpeg" && imgType != ".png") {
                layer.alert("您上传图片的类型不符合(.jpg|.jpeg|.gif|.png)！");
                picObjse.value = '';
                return false;
            }
            if (($("#AjaxFileData")[0].files[0].size / 1024) > (5 * 1024)) {
                layer.alert("上传图片不得大于 5M");
                picObjse.value = '';
                return false;
            }
            console.log('picFiles===v',picFilese);
            formDatas.append("file", picFilese);
            console.log('formData=2=vv',formDatas);

            $.ajax({
                url: '/seller/upload',
                type: 'POST',
                header: {
                    'content-type': 'multipart/form-data;'
                }, // 设置请求的 header
                processData:false,
                contentType: false,
               // cache:false,
                data: formDatas,
                //contentType: 'multipart/form-data',
                success: function (res) {
                    console.log("ok==res",res);
                    //console.log("ok==res.data",res.data);
                    var data = res.data,
                        _pic = data.split('upload/')[1];//JSON.parse(res.data).data;
                    console.log('data==v',data);
                    $("input[name='businessLicenseFile']").val(_pic);
                }
            });
        }

    });
    
    
  //文档上传
    var formData = new FormData(),
        picFiles = '',
    picObjs = document.getElementById("contractFileData");
    $("#contractFileData").change(function(){
        //$("#picShow").attr("src",URL.createObjectURL($(this)[0].files[0]));
        var file = $('#contractFileData').get(0).files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        console.log('picObjs.value-1--v',picObjs.value);

        if(picObjs.value != ""){ //
            picFiles = $("#contractFileData")[0].files[0];
            var imgType = (picFiles.name.substr(picFiles.name.lastIndexOf("."))).toLowerCase();
            if (imgType != ".doc" && imgType != ".docx" && imgType != ".pdf") {
                layer.alert("您上传的文件类型不符合(.doc|.docx|.pdf)！");
                picObjs.value = '';
                return false;
            }
            
            if (($("#contractFileData")[0].files[0].size / 1024) > (10 * 1024)) {
                layer.alert("上传图片不得大于10M");
                picObjs.value = '';
                return false;
            }
            
            console.log('picFiles===v',picFiles);
            formData.append("file", picFiles);
            console.log('formData=2=vv',formData);

            $.ajax({
                url: '/seller/upload',
                type: 'POST',
                header: {
                    'content-type': 'multipart/form-data;'
                }, // 设置请求的 header
                processData:false,
                contentType: false,
               // cache:false,
                data: formData,
                //contentType: 'multipart/form-data',
                success: function (res) {
                    console.log("ok==res",res);
                    //console.log("ok==res.data",res.data);
                    var data = res.data,
                        _pic = data.split('upload/')[1];//JSON.parse(res.data).data;
                    console.log('data==v',data);
                    $("input[name='contractFile']").val(_pic);
                }
            });
        }

    });




    //日期选择器
    laydate.render({
        elem: '#inputStartDate',
        format: "yyyy-MM-dd HH:mm:ss",
        type: 'datetime',
        trigger: 'click'
    });
    
  //日期选择器
    laydate.render({
        elem: '#inputEndDate',
        format: "yyyy-MM-dd",
        trigger: 'click'
    });
});

function show_img(t) {
    var $ = layui.jquery;
    console.log("----->",$)
    //var t = this_(t).find("img");
    //页面层
    layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['80%', '80%'], //宽高
        shadeClose: true, //开启遮罩关闭
        end: function (index, layero) {
            return false;
        },
        content: '<div style="text-align:center"><img src="' + $(t).attr('src') + '" /></div>'
    });
}
//定义serializeObject方法，序列化表单
$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [ o[this.name] ];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
/**
 * 提交保存
 */
var saveClickNum =0;//点击保存次数，防止重复点击；
function sellerFormSave() {
    let sellerForm = $("#sellerForm").serializeObject();
    
    var reg = /^1\d{10}$/;
    if(!reg.test(sellerForm.sellerMobile)){
        layer.msg('请输入正确的手机号',{icon: 5});
        saveClickNum =0;
        return false;
    }
    var picObjs = document.getElementById("AjaxFileData");
    var businessLicenseFile_ = document.getElementById("businessLicenseFile_");
    if(picObjs.value == "" && (businessLicenseFile_ == "" || businessLicenseFile_ == undefined || businessLicenseFile_ == "null" || businessLicenseFile_ == null)){
        layer.msg('请上传营业执照',{icon: 5});
        saveClickNum =0;
        return false;
    }
    
    var adoptIp=$("#adoptIp").val();
    var result=adoptIp.split(",");
    
    if(result.length > 5){
    	layer.msg('最多只能输入5个ip',{icon: 5});
    	saveClickNum =0;
        return false;
    }
    
    var contractFile = $("#contractFile").val();
    console.log(contractFile);
    if(contractFile == "" || contractFile == null){
    	layer.msg('请上传签约合同',{icon: 5});
    	saveClickNum =0;
        return false;
    }
    
    var maxPay = 99300,
        maxPayObj = $("input[name='maxPay']").val();
    if(maxPayObj > maxPay){
        layer.msg('最大薪酬不能超过'+maxPay,{icon: 5});
        saveClickNum =0;
        return false;
    }
    if($("input[name='serviceType']").val() == ""){
        layer.msg('请设置服务类型',{icon: 5});
        saveClickNum =0;
        return false;
    }

    save();
}

function sure(){
    var serviceTypes = "";

    $('input[type=checkbox]:checked').each(function() {
        serviceTypes += $(this).val() + ",";
    });

    $("input[name='serviceType']").val(serviceTypes.substring(0,serviceTypes.length-1));
}

function save(){
    console.log('saveClickNum---v',saveClickNum)
    if(saveClickNum>0){
        return false;
    }
    saveClickNum++;
    let _phoneId = $("input[name='sellerMobile']").val();
    $("input[name='loginId']").val(_phoneId);
    $("input[name='loginName']").val(_phoneId);
	let sellerForm = $("#sellerForm").serializeObject();
    $.post("/seller/saveSeller", sellerForm, function (data) {//ctx
    	if(data.flag){
	        layer.msg("保存成功", {icon: 1, time: 2000}, function(){
	        	var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
	        	parent.layer.close(index); //再执行关闭
	        	window.parent.$("#queryBySellerNameBtn").click();
	        });
    	} else {
    		saveClickNum =0;
    		layer.msg(data.msg, {icon: 5}); 
    	}
    });
}